// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const ejs = require('ejs');
const templateOptions = require('./template');
const templateFileOptions = require('./template/file');

// This method is called when your extension is activated
// Your extension is activated the very first time the command is executed

/**
 * @param {vscode.ExtensionContext} context
 */
function activate(context) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "do-template" is now active!');
	console.log('开始')

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with  registerCommand
	// The commandId parameter must match the command field in package.json
	// 注册命令
	const disposable = vscode.commands.registerCommand('do-template.helloWorld', function () {
		// The code you place here will be executed every time your command is executed

		// Display a message box to the user
		vscode.window.showInformationMessage('Hello World from !');
	});

	context.subscriptions.push(disposable);

	//右击目录
	const rightClickCommand = vscode.commands.registerCommand('do-template.rightClickCommand', async function (uri) {
		//被右键点击的文件或文件夹路径
		vscode.window.showInformationMessage(`Right Click Command executed on: ${uri.fsPath}`);
		console.log('URI:', uri.fsPath);

		//选择模板
		const options = templateOptions.map(v => { return v.title });
		const selection = await vscode.window.showQuickPick(options, {
			placeHolder: '选择模板'
		});
		const selectionOption = templateOptions.filter(v => {
			return v.title == selection
		})[0]

		//文件名
		if (selectionOption) {
			const fileName = await vscode.window.showInputBox({
				placeHolder: '请输入文件名称'
			});
			if (fileName) {
				//创建文件
				createTemplateFiles({
					templateDir: path.join(context.extensionPath, selectionOption.templateDir),
					templateFiles: selectionOption.templateFiles,
					uri: uri,
					createFilename: fileName,
				});
			}
		}
	});

	context.subscriptions.push(rightClickCommand);

	//右击文件
	const rightClickFileCommand = vscode.commands.registerCommand('do-template.rightClickFileCommand', async function (uri) {
		try {
			//选择模板
			const options = templateFileOptions.map(v => { return v.title });
			const selection = await vscode.window.showQuickPick(options, {
				placeHolder: '选择文件模板'
			});
			const selectionOption = templateFileOptions.filter(v => {
				return v.title == selection
			})[0]
			if (!selectionOption) return;

			// 获取文件信息
			const filePath = uri.fsPath;
			const fileName = path.basename(filePath, path.extname(filePath));
			const dirName = path.dirname(filePath).split(path.sep).pop();
			const className = `${dirName}-${fileName}-page`.toLowerCase();
			const params = {
				// uri: uri,
				// fileName: fileName,
				// dirName: dirName,
				className:className,
			};

			// 获取模板内容
			const templateContent = await getTemplateContent(selectionOption, context,params);

			// 插入内容到编辑器
			let editor = vscode.window.activeTextEditor;
			if (editor) {
				await editor.edit(editBuilder => {
					editor.selection.isEmpty
						? editBuilder.insert(editor.selection.active, templateContent)
						: editBuilder.replace(editor.selection, templateContent);
				});
				vscode.window.showInformationMessage('模板内容已插入');
			}
		} catch (error) {
			vscode.window.showErrorMessage(`插入文本失败: ${error.message}`);
			console.error('插入文本失败:', error);
		}
	});
	context.subscriptions.push(rightClickFileCommand);
}

// This method is called when your extension is deactivated
function deactivate() { }

//创建文件
function createTemplateFiles({ templateDir, templateFiles, uri, createFilename }) {
	console.log('执行', { templateDir, templateFiles, uri, createFilename });
	for (const templateFile of templateFiles) {
		const ext = path.extname(templateFile);//后缀名
		const newFilename = `${createFilename}${ext}`;//新建文件名
		const templatePath = path.join(templateDir, templateFile);//模板文件路径
		const filePath = path.join(uri.fsPath, newFilename);//新建文件路径
		const capitalizedFilename = createFilename.charAt(0).toUpperCase() + createFilename.slice(1);//首字母大写的文件名
		try {
			const templateContent = fs.readFileSync(templatePath, 'utf-8');
			const templateParams = {
				fileName: createFilename,
				FileName: capitalizedFilename,
			}
			console.log('测试', templateParams)
			const content = ejs.render(templateContent, templateParams)
			fs.writeFileSync(filePath, content);
			vscode.window.showInformationMessage(`Created ${newFilename} at ${uri.fsPath}`);
		} catch (error) {
			vscode.window.showErrorMessage(`Error creating ${newFilename}: ${error.message}`);
			console.error(`Error creating ${newFilename}:`, error);
		}
	}
}

//获取模板内容
function getTemplateContent(selectionOption, context, params) {
	return new Promise((resolve, reject) => {
		const templateDir = path.join(context.extensionPath, selectionOption.templateDir);
		const templateFiles = selectionOption.templateFiles;
		const templatePath = path.join(templateDir, templateFiles);
		fs.readFile(templatePath, 'utf-8', (err, data) => {
			if (err) {
				reject(err);
			} else {
				const templateParams = {
					className: params.className,
				}
				const content = ejs.render(data, templateParams)
				resolve(content);
			}
		});
	});
}


module.exports = {
	activate,
	deactivate
}
